package fr.upmc.i3s.upmcontact.views.fragments.models;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import fr.upmc.i3s.upmcontact.R;
import fr.upmc.i3s.upmcontact.backend.BackEndBridge;

public class PageFragmentModel extends Fragment {

	public static final String EXTRA_LAYOUT_FRAGMENT = "extra.layout.fragment";
	public static final String EXTRA_HEAD_ICON = "extra.head.icon";
	public static final String EXTRA_HEAD_TEXT = "extra.head.text";

	private View view;

	private TextView tvHeader;
	private ImageView ivHeader;

	private int mLayoutFragmentRes;
	private int mTextHeaderRes;
	private int mIconHeaderRes;

	private BackEndBridge backEndInstance;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if(view != null) {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		try {
//			if (savedInstanceState != null) {
//				mLayoutFragmentRes = savedInstanceState.getInt(EXTRA_LAYOUT_FRAGMENT);
//				mTextHeaderRes = savedInstanceState.getInt(EXTRA_HEAD_TEXT);
//				mIconHeaderRes = savedInstanceState.getInt("EXTRA_HEAD_ICON");
//			} else {
				if(getArguments() != null) {
					mLayoutFragmentRes = getArguments().getInt(EXTRA_LAYOUT_FRAGMENT);
					mTextHeaderRes = getArguments().getInt(EXTRA_HEAD_TEXT);
					mIconHeaderRes = getArguments().getInt(EXTRA_HEAD_ICON);
				}
//			}
			view = inflater.inflate(mLayoutFragmentRes, null);
		} catch (InflateException e) {
			/* view is already there, just return view as it is */
		}
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		initFragmentViews();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(EXTRA_LAYOUT_FRAGMENT, mLayoutFragmentRes);
		outState.putInt(EXTRA_HEAD_TEXT, mTextHeaderRes);
		outState.putInt(EXTRA_HEAD_ICON, mIconHeaderRes);
	}

	private void fetchViews() {
		this.tvHeader = (TextView) this.getView().findViewById(R.id.textView_header_text);
		this.ivHeader = (ImageView) this.getView().findViewById(R.id.imageView_header_icon);
	}

	private void customHeaderFragment() {
		this.tvHeader.setText(this.getActivity().getString(mTextHeaderRes));
		if(mIconHeaderRes!=0) {
			this.ivHeader.setVisibility(View.VISIBLE);
			this.ivHeader.setImageResource(mIconHeaderRes);
		} else {
			this.ivHeader.setVisibility(View.GONE);
		}
	}

	protected void initFragmentViews() {
		fetchViews();
		customHeaderFragment();
	}

	public BackEndBridge getBackEndInstance() {
		return backEndInstance;
	}

}
